package com.dao;


import com.dao.EnrollmentDAO;
import com.model.Enrollment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.dao.EmptyResultDataAccessException;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class EnrollmentDAOImpl implements EnrollmentDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 定义 SQL 语句
    private static final String SQL_FIND_ALL = "SELECT * FROM enrollment";
    private static final String SQL_FIND_BY_ID = "SELECT * FROM enrollment WHERE enroll_id = ?";
    private static final String SQL_INSERT = "INSERT INTO enrollment (user_id, course_id, enroll_state) VALUES (?, ?, ?)";
    private static final String SQL_UPDATE = "UPDATE enrollment SET user_id = ?, course_id = ?, enroll_state = ? WHERE enroll_id = ?";
    private static final String SQL_DELETE = "DELETE FROM enrollment WHERE enroll_id = ?";

//  RowMapper 将 ResultSet 中的每一行数据转换成一个 Course 对象
    private static final RowMapper<Enrollment> ROW_MAPPER = (ResultSet rs, int rowNum) -> {
        Enrollment enrollment = new Enrollment();
        enrollment.setEnrollId(rs.getInt("enroll_id"));
        enrollment.setUserId(rs.getInt("user_id"));
        enrollment.setCourseId(rs.getInt("course_id"));
        enrollment.setEnrollState(rs.getString("enroll_state"));
        return enrollment;
    };

    // CRUD 方法
/* 查找全部数据 */
    @Override
    public List<Enrollment> findAll() {
        return jdbcTemplate.query(SQL_FIND_ALL, ROW_MAPPER);
    }

    @Override  /* 根据ID查找数据 */
    public Enrollment findById(Integer id) {
        try {
            return jdbcTemplate.queryForObject(SQL_FIND_BY_ID, new Object[]{id}, ROW_MAPPER);
        } catch (EmptyResultDataAccessException e) {
            return null; // 或者抛出自定义异常
        }
    }
    /* 新增数据 */
    @Override
    public void save(Enrollment enrollment) {
        jdbcTemplate.update(SQL_INSERT,
                enrollment.getUserId(),
                enrollment.getCourseId(),
                enrollment.getEnrollState());
    }
/* 更新数据 */
    @Override
    public void update(Enrollment enrollment) {
        jdbcTemplate.update(SQL_UPDATE,
                enrollment.getUserId(),
                enrollment.getCourseId(),
                enrollment.getEnrollState(),
                enrollment.getEnrollId());
    }
/* 根据id删除数据 */
    @Override
    public void deleteById(Integer id) {
        jdbcTemplate.update(SQL_DELETE, id);
    }
}